#!/bin/bash
set -e -x

source $(dirname $0)/version.sh

cd $(dirname $0)/..

./scripts/download

rm -rf bin/crictl bin/kubectl bin/k3s-agent bin/k3s-server bin/kubectl bin/k3s build/data
ln -s containerd bin/k3s-agent
ln -s containerd bin/k3s-server
ln -s containerd bin/kubectl
ln -s containerd bin/crictl
for i in bridge flannel host-local loopback portmap; do
    if [ -e ./bin/$i ]; then
        rm -f ./bin/$i
    fi
    ln -s cni ./bin/$i
done


rm -rf build/data
mkdir -p build/data build/out
mkdir -p dist/artifacts

tar cvzf ./build/out/data.tar.gz --exclude ./bin/hyperkube ./bin
HASH=$(sha256sum ./build/out/data.tar.gz | awk '{print $1}')

cp ./build/out/data.tar.gz ./build/data/${HASH}.tgz

BIN_SUFFIX="-${ARCH}"
if [ ${ARCH} = amd64 ]; then
    BIN_SUFFIX=""
elif [ ${ARCH} = arm ]; then
    BIN_SUFFIX="-armhf"
fi

cp -f ./bin/hyperkube dist/artifacts/hyperkube${BIN_SUFFIX}
CMD_NAME=dist/artifacts/k3s${BIN_SUFFIX}

go generate
LDFLAGS="-X github.com/rancher/k3s/version.Version=$VERSION -w -s"
STATIC="-extldflags '-static'"
CGO_ENABLED=0 go build -ldflags "$LDFLAGS $STATIC" -o ${CMD_NAME} ./cmd/k3s/main.go
